﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BFlatCompile.Nodes
{
	public class CodeBlock
	{
		public static Executable[] ParseSwitchCase(Tokens tokens)
		{
			List<Executable> lines = new List<Executable>();
			while (true)
			{
				bool lastLine = false;
				string next = tokens.Peek();
				if (next == "break" ||
					next == "return")
				{
					lastLine = true;
				}
				else if (
				  next == "case" ||
				  next == "default")
				{
					return lines.ToArray();
				}

				if (next == "}")
				{
					tokens.PopExpected("return", "break");
				}

				lines.AddRange(CodeBlock.Parse(tokens, false));

				if (lastLine)
				{
					return lines.ToArray();
				}
			}
		}

		public static Executable[] Parse(Tokens tokens, bool bracketsRequired)
		{
			bool brackets;

			if (bracketsRequired)
			{
				tokens.PopExpected("{");
				brackets = true;
			}
			else
			{
				brackets = tokens.PopIfPresent("{");
			}

			if (!brackets)
			{
				Executable line = Executable.Parse(tokens, true, true);
				return new Executable[] { line };
			}
			else
			{
				List<Executable> lines = new List<Executable>();
				while (tokens.Peek() != "}")
				{
					Executable line = Executable.Parse(tokens, true, true);
					lines.Add(line);
				}

				tokens.PopExpected("}");

				return lines.ToArray();
			}
		}
	}
}
